<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\RegisterForm;
use app\models\Users;
use app\models\User;
use app\models\Qa;
use app\models\Article;
use app\models\Comments;
use app\models\Collect;
use app\models\Attention;
use yii\data\Pagination;

class UserController extends BaseController {

    /**
     * 行为（权限）
     * @return type
     */
    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'collect', 'attention', 'qa', 'article', 'comment'],
                'rules' => [
                    [
                        'actions' => ['logout', 'collect', 'attention', 'qa', 'article', 'comment'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['get','post'],
                ],
            ],
        ];
    }

    public function actions() {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionIndex() {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(Yii::$app->homeUrl);
        }

        //1、获取用户信息
        $uid = Yii::$app->user->identity->id;
        $user = Users::findOne(['id' => $uid]);

        //2、获取用户问答
        $qa_num = Qa::find()->where(['status' => '1', 'uid' => $uid])->count();
        $article_num = Article::find()->where(['status' => '1', 'uid' => $uid])->count();
        $comment_num = Comments::find()->where(['uid' => $uid])->count();
        return $this->render('index', ['user' => $user, 'qa_num' => $qa_num, 'article_num' => $article_num, 'comment_num' => $comment_num]);
    }

    /**
     * 登录
     * @return type
     */
    public function actionLogin() {
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            //登陆成功，通过session记录用户信息
            $model_user = new User();
            $user = $model_user->findByUsername(Yii::$app->user->identity->username);
            $session = Yii::$app->session;
            $session['users.id'] = 5;
            $session['users.username'] = $user->username;
            $session['users.email'] = $user->email;
            return $this->goBack();
        } else {
            return $this->render('login', ['model' => $model,]);
        }
    }

    /**
     * 注册
     */
    public function actionRegister() {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new RegisterForm();
        if ($model->load(Yii::$app->request->post()) && $model->register()) {
            return $this->redirect('/user/login');
        } else {
            return $this->render('register', ['model' => $model,]);
        }
    }

    /*
     * 退出登录
     */

    public function actionLogout() {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * -------------------------------------------------------------
     * 用户中心
     * 
     */

    /**
     * 用户的问答
     * @return type
     */
    public function actionQa() {
        $uid = Yii::$app->user->identity->id;
        //获取最新列表
        $query = Qa::find()->where(['status' => '1', 'uid' => $uid]);
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count()]);
        $qa_list = $query->offset($pages->offset)
                ->limit($pages->limit)
                ->orderBy('id desc')
                ->all();

        return $this->render('qa', ['qa_list' => $qa_list, 'pages' => $pages]);
    }

    /**
     * 用户的文章
     * @return type
     */
    public function actionArticle() {
        $uid = Yii::$app->user->identity->id;
        //获取最新列表
        $query = Article::find()->where(['status' => '1', 'uid' => $uid]);
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count()]);
        $article_list = $query->offset($pages->offset)
                ->limit($pages->limit)
                ->orderBy('id desc')
                ->all();

        return $this->render('article', ['article_list' => $article_list, 'pages' => $pages]);
    }

    /**
     * 用户的评论
     * @return type
     */
    public function actionComment() {
        $uid = Yii::$app->user->identity->id;
        //获取最新列表
        $query = Comments::find()->where(['status' => '1', 'uid' => $uid]);
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count()]);
        $comment_list = $query->offset($pages->offset)
                ->limit($pages->limit)
                ->orderBy('id desc')
                ->all();

        return $this->render('comment', ['comment_list' => $comment_list, 'pages' => $pages]);
    }

    /**
     * 用户的收藏
     * @return type
     */
    public function actionCollect() {
        $uid = Yii::$app->user->identity->id;
        //获取最新列表
        $query = Collect::find()->where(['uid' => $uid])->with('article');
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count()]);
        $collect_list = $query->offset($pages->offset)
                ->limit($pages->limit)
                ->all();

        return $this->render('collect', ['collect_list' => $collect_list, 'pages' => $pages]);
    }

    /**
     * 用户的关注
     * @return type
     */
    public function actionAttention() {
        $uid = Yii::$app->user->identity->id;
        //获取最新列表
        $query = Attention::find()->where(['uid' => $uid])->with('qa');
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count()]);
        $attention_list = $query->offset($pages->offset)
                ->limit($pages->limit)
                ->all();

        return $this->render('attention', ['attention_list' => $attention_list, 'pages' => $pages]);
    }

    /**
     * 邀请
     * @return type
     */
    public function actionInvitation() {
        return $this->render('invitation');
    }

    /**
     * 编辑用户
     */
    public function actionEdit() {
        //用户model
        $id = Yii::$app->user->identity->id;
        $model = $this->findModel($id);
        //初始化值
        $model->password = '';
        $model->password_confirm = '';

        if ($model->load(Yii::$app->request->post()) && $model->edit(Yii::$app->request->post(), $model)) {
            return $this->redirect(['index']);
        } else {
            return $this->render('edit', ['model' => $model,]);
        }
    }

    protected function findModel($id) {
        if (($model = Users::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('不存在的用户.');
        }
    }

    /**
     * 查看用户
     */
    public function actionView($id) {
        //1、获取用户信息
        $uid = $id;
        $user = Users::findOne(['id' => $uid]);

        //2、获取用户问答
        $qa_num = Qa::find()->where(['status' => '1', 'uid' => $uid])->count();
        $article_num = Article::find()->where(['status' => '1', 'uid' => $uid])->count();
        $comment_num = Comments::find()->where(['uid' => $uid])->count();
        return $this->render('view', ['user' => $user, 'qa_num' => $qa_num, 'article_num' => $article_num, 'comment_num' => $comment_num]);
    }

}
